package org.yufan.service.impl;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.yufan.bean.User;
import org.yufan.common.JedisService;
import org.yufan.exception.CustomException;
import org.yufan.mapper.UserMapper;
import org.yufan.service.SMSService;
import org.yufan.service.UserService;
import org.yufan.utils.JsonUtils;

import java.util.Date;

/**
 * Created by zxd on 2018/3/29.
 */
@Service("userService")
public class UserServiceImpl implements UserService{

    private static final String USER_LOGIN="user_login:";

    private Logger LOGGER= LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private JedisService jedisService;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(User user) throws CustomException {
        //1.用户名  2.电话号码不能重复
        if(queryByUser(user.getUsername())!=null){
            LOGGER.info("用户名已经被注册了,用户名是{}.",user.getUsername());
            throw  new CustomException("用户名已经被注册了!");
        }
        if(queryByPhone(user.getPhone())!=null){
            LOGGER.info("用户名已经被注册了,用户名是{}.",user.getUsername());
            throw  new CustomException("用户名已经被注册了!");
        }
        //TODO邮箱
        //2.加密
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        user.setCreated(new Date());
        user.setUpdated(user.getCreated());
        //3.保存
        userMapper.insertSelective(user);
    }

    public User queryByPhone(String phone) {
        User record=new User();
        record.setPhone(phone);
        return userMapper.selectOne(record);
    }

    @Override
    public Boolean check(String param, Integer type) throws CustomException {
        if(type<1||type>3){
            LOGGER.error("参数类型为{}",type);
            throw  new CustomException("错误的参数类型!");
        }
        User record=new User();
        switch (type){
            case 1:
                record.setUsername(param);
                break;
            case  2:
                record.setPhone(param);
                break;
            case 3:
                record.setEmail(param);
        }
        return userMapper.selectOne(record)!=null;
    }

    private User queryByUser(String username) {
        User record=new User();
        record.setUsername(username);
        return userMapper.selectOne(record);
    }

    @Override
    public String login(String username, String password) throws CustomException {
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            LOGGER.info("登录接口参数为空!");
            throw new CustomException("登录接口参数为空");
        }
        //根据用户米和密码(加密)找到用户
        User record=new User();
        record.setUsername(username);
        record.setPassword(DigestUtils.md5Hex(password));
        User user = userMapper.selectOne(record);
        if(user==null){
            //用户米密码错误
            LOGGER.info("用户名密码错误!");
            throw new CustomException("用户名密码错误!");
        }
        return dealLogin(username, user);
    }

    private String dealLogin(String username, User user) {
        //处理登录
        //生成token
        String token= DigestUtils.md5Hex(new Date().toString()+username);
        //设置登录信息到redis服务器
        jedisService.set(USER_LOGIN+token, JsonUtils.objectToJson(user));
        LOGGER.info("当前登录用户{}，token为{}",username,token);
        //设置过期时间
        jedisService.expire(USER_LOGIN+token,60*60*2);
        return token;
    }

    @Override
    public String loginByPhone(String phone, String sms_code) throws CustomException {
        //1.校验验证码
        String service_code = jedisService.get(SMSService.SMS +
                SMSService.LOGIN_SMS + phone);
        if(StringUtils.isEmpty(service_code)){
            LOGGER.error("电话{},验证码过期",phone);
            throw  new CustomException("验证码过期了!");
        }
        if(!service_code.equals(sms_code)){
            LOGGER.error("电话{},验证码输入错误!");
            throw  new CustomException("对不起，验证码输入错误");
        }
        //处理登录
        User user=queryByPhone(phone);
        if(user==null){
            throw  new CustomException("对不起，手机号码没有注册!");
        }
        return dealLogin(user.getUsername(), user);
    }


    @Override
    public User queryUserByToken(String token) throws CustomException {
        LOGGER.info("当前查询用户信息的token为{}",token);
        String json = jedisService.get(USER_LOGIN + token);
        if(StringUtils.isEmpty(json)){
            LOGGER.info("用户登录失效,token{}",token);
            throw  new CustomException("用户登录失效!");
        }
        //更新过期时间
        jedisService.expire(USER_LOGIN+token,60*60*2);
        return JsonUtils.jsonToPojo(json,User.class);
    }
}


